import router from "./index.ts";
import {NavigationGuardNext, RouteLocationNormalized, RouteRecordRaw} from "vue-router";
import usePermissionStore from "../store/modules/permission.ts";
import useUserStore from "../store/modules/user.ts";
import { asyncRouterMap } from "./asyncRouterMap.ts";

// 白名单，免登录
const whiteList: string[] = ['login', '404']

// @ts-ignore
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
    // console.log(to, from)
    const token = localStorage.getItem('token')
    if (!token) {
        if (whiteList.includes(<string>to.name)) {
            next()
        } else {
            next('/login')
        }
    } else {
        if (to.path === '/login') {
            next('/')
        } else {
            const permissionStore = usePermissionStore()
            const userStore = useUserStore()
            const permissionCodeList: string[] = permissionStore.permissionCodeList
            if (permissionCodeList.length === 0) {
                const userInfo = userStore.getUserInfo()
                permissionStore.addRoutes().then((res:RouteRecordRaw[]) => {
                    res.forEach((v:RouteRecordRaw):void => {
                        console.log(v);
                        router.addRoute(v)
                    })
                    console.log(router.getRoutes())
                })
                // console.log(asyncRouters);
                // asyncRouters.forEach((v: any) => {
                //     router.addRoute(v)
                // })
                // console.log(router)
            } else {
                next()
            }

            // if (permission) {
            //
            // }
            // permission && permission.indexOf(<string>to.meta.code) === -1 ? next('/404') : next()
        }
    }
})